package com.xjh.serverinspect.security.advice;

import com.xjh.serverinspect.security.AESUtils;
import com.xjh.serverinspect.security.RSAUtils;
import com.xjh.serverinspect.security.RequestBodyHandler;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 解密请求参数的HttpServletRequestWrapper
 * </p>
 *
 * @author xujinghui
 * @since 2024-12-20
 */
public class DecryptingHttpServletRequestWrapper extends HttpServletRequestWrapper {

    private Map<String, String[]> decryptedParameterMap;

    public DecryptingHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
        // 从原始请求中获取所有参数
        Map<String, String[]> originalParams = new HashMap<>(request.getParameterMap());

        String encodeAesKey = request.getHeader("X-Encrypt");
        if (!StringUtils.isEmpty(encodeAesKey)) {
            try {
                String aesKey = RSAUtils.decryptByPrivateKey(encodeAesKey, RequestBodyHandler.PRIVATE_KEY);
                this.decryptedParameterMap = new HashMap<>();
                for (Map.Entry<String, String[]> entry : originalParams.entrySet()) {
                    String[] values = entry.getValue();
                    String[] decryptedValues = new String[values.length];
                    for (int i = 0; i < values.length; i++) {
                        decryptedValues[i] = AESUtils.decrypt(values[i], aesKey);
                    }
                    decryptedParameterMap.put(entry.getKey(), decryptedValues);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

    }

    @Override
    public String[] getParameterValues(String name) {
        return decryptedParameterMap.get(name);
    }

    @Override
    public Enumeration<String> getParameterNames() {
        return Collections.enumeration(decryptedParameterMap.keySet());
    }

    @Override
    public String getParameter(String name) {
        String[] values = decryptedParameterMap.get(name);
        return values != null && values.length > 0 ? values[0] : null;
    }

}
